package com.raymond.client.handler;

import com.raymond.client.msg.MessageManages;
import com.raymond.client.msg.response.BaseResponseMessage;
import com.raymond.client.session.WindowManager;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 业务处理基础类
 *
 * @author :  raymond
 * @version :  V1.0
 * @date :  2021-07-19 11:39
 */
public class RespBusinessHandler extends SimpleChannelInboundHandler<BaseResponseMessage>{

    private final static Logger logger = LoggerFactory.getLogger(RespBusinessHandler.class);

    /**
     * 消息管理器
     */
    private final WindowManager msgManager;

    public RespBusinessHandler(WindowManager msgManager) {
        this.msgManager = msgManager;
    }

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, BaseResponseMessage msg) {
        responseNotice(msg);
    }


    /**
     * 找到对应的请求通知
     * @param resp 响应
     */
    private void responseNotice(BaseResponseMessage resp) {
        MessageManages remove = msgManager.remove(resp.getSequenceId());
        if (remove != null) {
            remove.success(resp);
        } else {
            notRequest(resp);
        }
    }

    /**
     * 当前消息找不到对应的请求
     * @param resp resp
     */
    private void notRequest(BaseResponseMessage resp) {
        logger.error("找不到响应,sequenceId:{},commandId:{}", resp.getSequenceId(), resp.getCommandId());
    }


}
